# 裁剪视频
import os
import cv2
def video2video(video_path,video_name,save_path = './',cut_span=[0,10]):
    frame_now =  0
    if video_name.strip():
        cap = cv2.VideoCapture(video_path)
        frame_num = cap.get(7) 
        FPS = int(cap.get(5))
        frame_w  = int(cap.get(3))
        frame_h  = int(cap.get(4))
        cut_span = [x*FPS for x in cut_span]
        print(frame_num,frame_w,frame_h,FPS)
        # if cut_span[1] > frame_num:
        #     return
        # print(cv2.CAP_PROP_POS_FRAMES)
        # cap.set(cv2.CAP_PROP_POS_FRAMES,cut_span[0])
        # frame_now = cut_span[0]
    # 创建视频
    # videoWriter = cv2.VideoWriter(save_path + video_name[:-4]+'_'+str(cut_span[0]) + '.mp4', cv2.VideoWriter_fourcc('M','P','E','G'), 20, (frame_w,frame_h))
    videoWriter = cv2.VideoWriter(save_path + video_name[:-5]+'_'+str(cut_span[0]) + '.mp4', cv2.VideoWriter_fourcc('M','P','4','V'), 20, (frame_w,frame_h))
    while frame_now < cut_span[1]:
        success, origin_img = cap.read()
        # print(frame_now)
        if not success or len(origin_img) < 2:
            break
        # print(origin_img.shape)
        frame_now +=1
        # if frame_now%frame_span != 0:
        #     continue
        if frame_now > cut_span[0] and frame_now < cut_span[1]:
            # cv2.imshow('origin_img',origin_img)
            # cv2.waitKey(100)
            cv2.imwrite(save_path+ video_name[:-5]+"_%.6d.jpg"%frame_now,origin_img)
            videoWriter.write(origin_img)
    videoWriter.release()
def main():
    video_path = './BeltTearVideo/20210103_174457.h264'
    save_image_path ='./image/'
    # start_end_time = [['00:06:42','00:06:46'],['00:09:21','00:09:25'],['00:11:28','00:11:32']]
    start_end_time = [['00:10:40','00:10:47']]
    video_name = os.path.split(video_path)[-1]
    print(video_name)
    if video_name.split('.')[-1] not in ['mp4','avi','h264']:
        return
    for span_time in start_end_time:
        start_time = span_time[0].split(':')
        start_time = int(start_time[0])*3600 + int(start_time[1])*60 + int(start_time[2])
        end_time = span_time[1].split(':')
        end_time = int(end_time[0])*3600 + int(end_time[1])*60 + int(end_time[2])
        print(end_time)
        if end_time < start_time:
            return
        video2video(video_path,video_name,save_image_path,[start_time,end_time])
        # break

if __name__ == "__main__":
    main()   

